<?php

	namespace Application\Controller;
	
	use Zend\Mvc\Controller\AbstractActionController;
	use Zend\View\Model\ViewModel;
	use Zend\Db\Adapter\Adapter as DbAdapter;
	use Application\Model\ServicesTable;
	use Application\Model\ProjetTable;
	use Application\Model\ProjetsUsersTable;
	use Zend\Mvc\MvcEvent;
	use Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack;
	use Zend\Session\Container;
	use Application\Form\ConnexionForm;
	use Application\Form\InputFileForm;
	use Application\Form\ProjetForm;
	use Application\Form\DemandeForm;
	use Application\Model\Intranet;
	use Application\Model\UserTable;
	use User\Controller\UserController;
	use Application\Model\FileDownload;
	use Application\Model\Demande;
	use Zend\Mail;
	use Zend\Form\Element\Date;
	use Application\Model\FileTable;
	use Application\Model\File;
	use Application\Model\PersonnelTable;
	use Application\Model\Personnel;
	use Application\Model\AgendaTable;
	use Application\Model\Agenda;
	use Application\Form\InscriptionForm;
	use Application\Model\Inscription;
	
	
	class AdminController extends AbstractActionController {
	
		protected $serviceTable;
		protected $userTable;
		protected $fileTable;
		protected $projetTable;
		protected $projetUserTable;
		protected $personnalTable;
		protected $agendaTable;
	
		
		public function adminAction() {
	
			date_default_timezone_set('UTC');
	
					$user_session = new Container('user');
					$id = $user_session->id_user;
					$login = $user_session->login;

					if(isset($user_session) && $user_session->is_connected == 1 && $user_session->is_admin ==1){
				
						if( $user_session->is_connected == 1 && $user_session->is_admin ==1)
						{
	
							$fileForm = new InputFileForm ();
							$demandeForm = new DemandeForm ();
							$projetForm  = new ProjetForm();
							$CV = $this->getFileTable()->getCVFile($id);
							$personnel =   $this->getPersonnelTable()->getPersonnellogin($login);
							$fichiersSources =   $this->getFileTable()->getFile($id,'Fichiers sources');
							$autresfichiers =   $this->getFileTable()->getFile($id,'Autres');
							
							$agenda   = $this->getAgendaTable()->getTacheByUserId($id);
	
							if($CV == null || $CV == "Error"){
								$CV = "Vous n'avez pas encore soumis votre CV. <br>";
							}
	
							if($fichiersSources == null || $fichiersSources == "Error"){
								$fichiersSources = "Vous n'avez pas encore de fichiers. <br>";
							}
							return new ViewModel ( array (
									'fileform' => $fileForm,
									'demandeform' => $demandeForm ,
									'projetForm' =>$projetForm,
									'projet' =>$this->getProjetTable()->SelectById($id),
									'projet2' =>$this->getProjetsUsersTable()->SelectByIdUsers($id),
									'fichiersSources' =>$fichiersSources,
									'autresfichiers' =>$autresfichiers,
									'CV' =>$CV,
									'personnel' => $personnel,
									'agenda' => $agenda,
							) );
				
						}else {
							
							return new ViewModel(array(
						'result'=>'<p style="padding-left: 8px;"> vous n\'avez pas les droits requis pour visiter cette page!
						<br><br>
    					<a href="#"> Cliquez ici pour revenir à la page d\'acceuil </a>
  
    					</p>
  
    					',
							));
						}
					} else {
				
						return $this->redirect ()->toRoute ( 'connexion', array (
								'controller' => 'Intranet',
								'action' => 'connexion'
						) );
					}
	
			//	return new ViewModel();
		}
		public function getUserTable() {
			if (! $this->userTable) {
				$sm = $this->getServiceLocator ();
				$config = $sm->get ( 'config' );
				$config = $config ['db'];
				$dbAdapter = new DbAdapter ( $config );
				// return $dbAdapter;
				$table = new UserTable ( $dbAdapter );
				// $this->userTable = $sm->get($table);
				$this->userTable = $table;
			}
			return $this->userTable;
		}
	
		public function getPersonnelTable() {
			if (! $this->personnalTable) {
				$sm = $this->getServiceLocator ();
				$config = $sm->get ( 'config' );
				$config = $config ['db'];
				$dbAdapter = new DbAdapter ( $config );
				// return $dbAdapter;
				$table = new PersonnelTable ( $dbAdapter );
				// $this->userTable = $sm->get($table);
				$this->personnalTable = $table;
			}
			return $this->personnalTable;
		}
	
		/*
		 * AGENDA
		 */
		
		public function getAgendaTable() {
			if (! $this->agendaTable) {
				$sm = $this->getServiceLocator ();
				$config = $sm->get ( 'config' );
				$config = $config ['db'];
				$dbAdapter = new DbAdapter ( $config );
				$table = new AgendaTable ( $dbAdapter );
				$this->agendaTable = $table;
			}
			return $this->agendaTable;
		}
		
		/**
		 * File table
		 */
		public function getFileTable() {
			if (! $this->fileTable) {
				$sm = $this->getServiceLocator ();
				$config = $sm->get ( 'config' );
				$config = $config ['db'];
				$dbAdapter = new DbAdapter ( $config );
				// return $dbAdapter;
				$table = new FileTable ( $dbAdapter );
				// $this->userTable = $sm->get($table);
				$this->fileTable = $table;
			}
			return $this->fileTable;
		}
	
		public function getProjetTable()
		{
			if (!$this->projetTable) {
				$sm = $this->getServiceLocator();
				$config = $sm->get('config');
				$config = $config['db'];
				$dbAdapter = new DbAdapter($config);
				//return $dbAdapter;
				$table = new ProjetTable($dbAdapter);
				//$this->userTable = $sm->get($table);
				$this->projetTable = $table;
			}
			return $this->projetTable;
		}
	
		public function getProjetsUsersTable()
		{
			if (!$this->projetUserTable) {
				$sm = $this->getServiceLocator();
				$config = $sm->get('config');
				$config = $config['db'];
				$dbAdapter = new DbAdapter($config);
				//return $dbAdapter;
				$table = new ProjetsUsersTable($dbAdapter);
				//$this->userTable = $sm->get($table);
				$this->projetUserTable = $table;
			}
			return $this->projetUserTable;
		}
	
		public function connexionAction() {
			$user_session = new Container('user');
	
			if ($user_session->is_connected == 0) {
				$form = new ConnexionForm();
				return new ViewModel ( array (
	
						'form' => $form
				) );
					
			} else {
					
				return $this->redirect ()->toRoute ( 'intranet' );
			}
		}
		public function deconnexionAction() {
			unset ( $_SESSION ['user'] );
	
			return $this->redirect ()->toRoute ( 'connexion', array (
					'controller' => 'Intranet',
					'action' => 'connexion'
			) );
		}
	
		 
		public  function demandeAction(){
	
			$demandeForm = new DemandeForm ();
	
			$request = $this->getRequest ();
	
			if ($request->isPost ()) {
		   
				$demand = new Demande();
				$demandeForm->setInputFilter ( $demand->getInputFilter () );
				$demandeForm->setData ( $request->getPost () );
		   
				if ($demandeForm->isValid ()) {
	
					$datas = $demandeForm->getData() ;
					//$datas->exchangeArray($form->getData());
	
					$typedemande = $datas['type_demande'];
					$demande = $datas['demande'];
	
					$mail = new Mail\Message(); //todo ajouter le nom du sender from session
					$mail->setBody($demande)
					->setFrom('somebody@example.com', 'TITI')
					->addTo('tijoscarlos@gmail.com','CARLOS')
					->setSubject($typedemande);
	
					//$request = $this->getRequest();
					$transport = new Mail\Transport\Sendmail();
					$transport->send($mail);
	
					$fileForm = new InputFileForm ();
					$result ='Votre demande a été envoyé avec succès';
					return new ViewModel(array(
							'fileform' =>$fileForm,
							'demandeform' =>$demandeForm,
							'result'      => $result,
					));
				}else{
					$fileForm = new InputFileForm ();
					//	$demandeForm = new DemandeForm ();
					return new ViewModel(array(
							'fileform' =>$fileForm,
							'demandeform' =>$demandeForm,
					));
				}
			}
	
		}
		 
		public function inscriptionAction(){
			 
			$form_insc = new InscriptionForm();
			$request = $this->getRequest ();
			if ($request->isPost ()) {
				 
				echo "is post";
				$sample = new Inscription();
				//$form_insc->setInputFilter($sample->getInputFilter());
				//$form_insc->setData($request->getPost());
		   
				print_r($request->getPost()['nom']);
				//if ($form_insc->isValid()) {
				$datas = $request->getPost();
				//echo "is valid";
				//$datas = $form_insc->getData() ;
				//$datas->exchangeArray($form->getData());
				 
				$nom  = $datas['nom'];
				$prenom  = $datas['prenom'];
				$fonction  = $datas['fonction'];
				$adresse  = $datas['adresse'];
				$email  = $datas['email'];
				$telephone = $datas['telephone'];
				$login = $datas['login'];
				$password  = $datas['password'];
				$password2  = $datas['password2'];
				 
				//	$objet  = $datas['motif'];
				$date_inscrip =  $datas['date_inscrip'];
				 
				//	echo isPasswordEqual($password,$password2);
				 
				if($password != $password2){
	
					$erreur = 'Erreur de confirmation du mot de passe';
					return new ViewModel(array(
							'form'=>$form_insc,
							'erreur' =>$erreur,
					));
				}
				 
				//$result = $this->getPersonnelTable()->addPersonnel($nom, $prenom, $fonction, $email, $telephone, $login, $password, $date_inscrip);
				try {
					$this->getPersonnelTable()->addPersonnel($nom, $prenom, $login,$fonction,$email, $telephone, md5($password),$adresse,$date_inscrip);
				} catch (\PDOException $e) {
					 
					throw new Exception\InvalidQueryException(
							'Statement could not be executed ',
							null,
							$e
					);
				}
				 
	
				return new ViewModel(array(
						'result'=>'<p style="padding-left: 8px;">Votre compte a été enregistré.Vous veillez attendre sa
    					 validation pour vous connecter <br><br> Merci <br><br>
    					<a href="#"> Cliquez ici pour revenir à la page d\'acceuil </a>
   
    					</p>
   
    					',
				));
			}
			return new ViewModel(array(
					'form'=>$form_insc,
			));
		}
		 
		public function downloadfileAction()
		{
	
			$user_session = new Container('user');
			$id_user = $user_session->id_user;
			if ($id_user != null){
				$dat_creat = date("Y-m-d");
				$today = date("Ymd");
		
				$typefichier = $_POST['typefile'];
		
		
				if ($typefichier == "Avatar") {
					$dossier ='../lamisa.burundi/public/img/avatar/';
				}elseif($typefichier == "CV") {
					$dossier ='CV';
				}else {
					$dossier ='projets/'.$today;
				}
			  
		
				$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
			  
				//print_r($_SERVER);
				if ($fn) {
		
					// AJAX call
					file_put_contents(
					'../lamisa.burundi/fichiers/'.$dossier.'/' . $fn,
					file_get_contents('php://input')
					);
			   
					exit();
		
				}
				else {
		
			   
		
					if (!file_exists($dossier)){
						mkdir($dossier, 0777, true);
					}
					 
					// form submit
		
					$files = $_FILES['fileselect'];
		
			   
					foreach ($files['error'] as $id => $err) {
						if ($err == UPLOAD_ERR_OK) {
							$fn = $files['name'][$id];
							 
							$infosfichier =pathinfo($fn);
							$extension_upload = $infosfichier['extension'];
		
							if($typefichier == "Avatar"){
		
								$fn = $id_user.'.'.$extension_upload;
							}
		
							if ($typefichier == "Avatar") {
		
								$fn = $id_user.'.'.$extension_upload;
								move_uploaded_file( $files['tmp_name'][$id],'../lamisa.burundi/public/img/avatar/'. $fn);
		
								$adress ='../lamisa.burundi/public/img/avatar/';
							}else{
		
								$adress = '/lamisa.burundi/fichiers/'.$dossier;
								move_uploaded_file( $files['tmp_name'][$id],'../lamisa.burundi/fichiers/'.$dossier.'/' . $fn);
							}
							 
							 
							 
							$this->getFileTable()->addFile( $id_user, $fn,$adress , $typefichier,$dat_creat);
							 
						}
					}
			   
					//return $this->redirect ()->toRoute ( 'intranet' );
					return $this->redirect ()->toRoute ( 'connexion', array (
							'controller' => 'Intranet',
							'action' => 'connexion',
							'params'=> $dossier
					) );
		
				}
				
			}else{
					return $this->redirect ()->toRoute ( 'connexion', array (
							'controller' => 'Intranet',
							'action' => 'connexion',
							'params'=> $dossier
					) );
					 
			}
	
		}
		
		
		public  function gestionrhAction(){	
			return new ViewModel();
		}
		 
}
